package com.lc.dmd.config.aspect;

import com.lc.dmd.config.datasource.DynamicDataSourceContextHolder;
import com.study.common.ano.DataSourceAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author: LChuang
 * @date: 2023/9/6 14:38
 * @description: 使用AOP特性拦截DataSourceAnnotation注解，切换数据源
 * EnableAspectJAutoProxy(proxyTargetClass = true)注解可将AOP自动代理从jdk代理改为cglib代理
 */
@Slf4j
@Aspect
@Component
@Order(1)
public class DataSourceAspect {

    @Pointcut("@annotation(com.study.common.ano.DataSourceAnnotation)")
    public void dsPointcut(){
    }

    @Around("dsPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSourceAnnotation dataSourceAnnotation = method.getAnnotation(DataSourceAnnotation.class);
        if (dataSourceAnnotation != null) {
            DynamicDataSourceContextHolder.setDataSourceType(dataSourceAnnotation.value().name());
        }
        try {
            Object result = point.proceed();
            log.info("切面执行结果：{}", result);
            return result;
        } finally {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

}
